package com.bot.adms.dao.impl;

import com.bot.adms.dao.IApplyContentDao;
import com.bot.adms.model.entity.ApplyContent;
import com.bot.adms.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 席浩
 * @version 1.0
 * 申请内容DAO实现类
 */
public class ApplyContentDaoImpl implements IApplyContentDao {

    private Connection conn;
    private Statement stmt;
    private ResultSet rs;


    /**
     * 添加申请内容
     *
     * @param applyContent 申请内容信息，包含：申请标题，分屏类型等等
     * @return Integer 添加成功的数量
     */
    @Override
    public Integer insertApplyContent(ApplyContent applyContent) {
        // 获取数据库连接
        int rows;
        try {
            //1.获取Connection连接
            conn = JdbcUtils.getConnection();
            //2.通过连接获取statement对象
            stmt = conn.createStatement();

            // 构建插入SQL（假设表名为apply_content，字段与实体类对应）
            String sql = "INSERT INTO `bo_adms`.`apply_content` (" +
                    " `title`, `sp_sc_type`, `lay_style`, `apply_id`" +
                    ") VALUES (" +

                    "'" + applyContent.getTitle() + "', " +  // 标题
                    applyContent.getSpScType() + ", " +  // 分屏类型（数值类型）
                    applyContent.getLayStyle() + ", " +  // 布局样式（数值类型）
                    applyContent.getApplyId() +  // 投放申请id（数值类型）
                    ")";
            System.out.println("执行插入SQL：" + sql);

            // 执行SQL
            rows = stmt.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.close(conn, stmt);
        }
        return rows;  // 插入成功返回true
    }


    /**
     * 修改申请内容
     *
     * @param applyContent 申请内容信息，包含：包含：申请标题，分屏类型等等
     * @return Integer 修改成功的数量
     */
    @Override
    public Integer updateApplyContent(ApplyContent applyContent) {
        // 获取数据库连接
        int rows;
        try {
            //1.获取Connection连接
            conn = JdbcUtils.getConnection();
            //2.通过连接获取statement对象
            stmt = conn.createStatement();
            // 构建更新SQL（根据id更新）
            String sql = "UPDATE `bo_adms`.`apply_content` SET " +
                    "`title` = '" + applyContent.getTitle().replace("'", "\\'") + "', " +  // 处理单引号转义
                    "`sp_sc_type` = " + applyContent.getSpScType() + ", " +
                    "`lay_style` = " + applyContent.getLayStyle() + ", " +
                    "`apply_id` = " + applyContent.getApplyId() + " " +
                    "WHERE `id` = " + applyContent.getId();
            System.out.println("执行更新SQL：" + sql);

            // 执行SQL
            rows = stmt.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.close(conn, stmt);
        }
        return rows;  // 更新成功返回true
    }

    /**
     * 删除申请内容
     *
     * @param id 申请内容id
     * @return Integer 删除成功的数量
     */
    @Override
    public Integer deleteApplyContent(Long id) {
        // 获取数据库连接
        int rows;
        try {
            //1.获取Connection连接
            conn = JdbcUtils.getConnection();
            //2.通过连接获取statement对象
            stmt = conn.createStatement();
            // 构建删除SQL
            String sql = "DELETE FROM `bo_adms`.`apply_content` " +
                    "WHERE `id` = " + id;  // 按主键id删除
            System.out.println("执行删除SQL：" + sql);

            // 执行SQL
            rows = stmt.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.close(conn, stmt);
        }
        return rows;  // 删除成功返回true

    }

    /**
     * 查找（获取）申请内容信息
     *
     * @param id 申请内容id
     * @return ApplyContent 申请内容信息，包含：申请标题，分屏类型等等
     */
    @Override
    public ApplyContent getApplyContentById(Long id){
        // 获取数据库连接
        try {
            //1.获取Connection连接
            conn = JdbcUtils.getConnection();
            //2.通过连接获取statement对象
            stmt = conn.createStatement();
        // 构建查询SQL
        String sql = "SELECT * FROM `bo_adms`.`apply_content` " +
                "WHERE `id` = " + id;
        System.out.println("执行查询SQL：" + sql);
        ApplyContent applyContent = null;

            rs = stmt.executeQuery(sql);
        // 遍历结果集（最多一条记录）
            if (rs.next()) {
                applyContent = new ApplyContent();
                // 封装结果到实体类（字段名与数据库列名对应）
                applyContent.setId(rs.getLong("id"));
                applyContent.setTitle(rs.getString("title"));
                applyContent.setSpScType(rs.getInt("sp_sc_type"));
                applyContent.setLayStyle(rs.getInt("lay_style"));
                applyContent.setApplyId(rs.getLong("apply_id"));
                System.out.println("查询到申请内容：" + applyContent);
            } else {
                System.out.println("未找到id为" + id + "的申请内容");
            }


        return applyContent;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }

    /**
     * 查询申请内容信息
     *
     * @param applyContent 申请内容信息，包含：申请标题，分屏类型等等
     * @return List<ApplyContent> 申请内容信息集合，包含：申请标题，分屏类型等等
     */
    @Override
    public List<ApplyContent>  searchApplyContent(ApplyContent applyContent) {
        // 获取数据库连接
        try {
            //1.获取Connection连接
            conn = JdbcUtils.getConnection();
            //2.通过连接获取statement对象
            stmt = conn.createStatement();
        // 构建动态查询SQL（多条件OR匹配）
        StringBuilder sql = new StringBuilder("SELECT * FROM `bo_adms`.`apply_content` WHERE 1=1 ");

        if (applyContent != null) {
            // id精确匹配
            if (applyContent.getId() != null) {
                sql.append("and `id` = ").append(applyContent.getId()).append(" ");
            }
            // 标题模糊匹配
            if (applyContent.getTitle() != null && !applyContent.getTitle().isEmpty()) {
                sql.append("and `title` LIKE '%").append(applyContent.getTitle()).append("%' ");
            }
            // 分屏类型精确匹配
            if (applyContent.getSpScType() != null) {
                sql.append("and `sp_sc_type` = ").append(applyContent.getSpScType()).append(" ");
            }
            // 布局样式精确匹配
            if (applyContent.getLayStyle() != null) {
                sql.append("and `lay_style` = ").append(applyContent.getLayStyle()).append(" ");
            }
            // 投放申请id精确匹配
            if (applyContent.getApplyId() != null) {
                sql.append("and `apply_id` = ").append(applyContent.getApplyId()).append(" ");
            }
        }

        // 处理无查询条件的情况
        String finalSql = sql.toString();
        if (finalSql.endsWith("WHERE 1=1 ")) {
            finalSql = finalSql.replace("WHERE 1=1 ", "");
        }
        System.out.println("执行搜索SQL：" + finalSql);

        ResultSet rs = null;
        List<ApplyContent> applyContentList = new ArrayList<>();
            rs = stmt.executeQuery(finalSql);

        // 遍历所有结果
            while (rs.next()) {
                ApplyContent content = new ApplyContent();
                content.setId(rs.getLong("id"));
                content.setTitle(rs.getString("title"));
                content.setSpScType(rs.getInt("sp_sc_type"));
                content.setLayStyle(rs.getInt("lay_style"));
                content.setApplyId(rs.getLong("apply_id"));
                applyContentList.add(content);
                System.out.println("查询到申请内容：" + content);
            }
        return applyContentList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }

    /**
     * 关闭数据库资源（Connection和Statement）
     */

}